package com.lincoln.framework.utils;

import com.lincoln.framework.annotation.JsonParse;
import com.lincoln.framework.annotation.JsonUnparse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import java.lang.reflect.Field;

/**
 * json封装工具类
 * 
 * @author zwm
 * 
 * @version 2016-2-24 上午11:26:55
 */
public class JSONUtilsEx {

	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(JSONUtilsEx.class);

	/**
	 * 提供json通用初始化配置，自动过滤实体类中manytoone且未JsonParse标注需要强制增加
	 * 
	 * @param excludes
	 *            不做json处理参数数组
	 * @return JsonConfig
	 */
	public static JsonConfig getJsonConfig(String[] excludes) {
		JsonConfig config = new JsonConfig();
		config.setAllowNonStringKeys(true);
		if (excludes != null && excludes.length > 0) {
			config.setExcludes(excludes);
		}
		config.setJsonPropertyFilter(new PropertyFilter() {
			@Override
			public boolean apply(Object source, String name, Object value) {
				Field field;
				try {
					if (source.getClass().isAnnotationPresent(Entity.class)) {
						try {
							field = source.getClass().getDeclaredField(name);
						} catch (NoSuchFieldException e) {
							return false;
						}
						if ((field.isAnnotationPresent(ManyToOne.class) && !field.isAnnotationPresent(JsonParse.class))
								|| field.isAnnotationPresent(JsonUnparse.class)) {
							return true;
						}
					}
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
				return false;
			}
		});
		return config;
	}

	/**
	 * 对象转JSONObject
	 */
	public static JSONObject fromObject(Object object, String[] excludes) {
		JsonConfig config = getJsonConfig(excludes);
		return JSONObject.fromObject(object, config);
	}

}
